<?php
namespace cubox;

class  Controller{
    public App $app;
    public string $name = '';
    public string $action = '';
    protected array $data = [];
    public array $gets = [];
    public array $posts = [];
    public bool $ajax = false;
    public function __construct()
    {
        $this->posts =  $_POST;
    }
    
    public function display(string $name=''){
        
        $themePath = ROOT.DS.APP.DS.$this->app->name.DS.'template';
        
        if (!$name) $name =  lcfirst($this->name).'_'.lcfirst($this->action);
        
        $path = $themePath.DS.$name;

        if (substr($path, -5)!=='.html') $path.='.html';

        $template = new Template($path, $this->data);

        return $template->getHtml();
    }

    public function __call($name, $arguments)
    {
        throw new \Exception('Controller Error:'.$name.' function does not exist');
    }

    public function set($key,$value){
        $this->data[$key] = $value;
    }

    public function cache(string $name=''): Cache{
        return $this->app->cache($name);
    }
    
    public function model(string $name):Model{
        return $this->app->model($name);
    }

    public function check(string $title=''):Check{
         return new Check($title);
    }

    /**
     * 获取POST的值
     * 
     * 第二个参数为Check 类型时，验证参数，其他类型为默认值
     * 
     * @param string $name
     * @param mixed $default | Check $check
     * @return mixed
     */
    public function post($name,int | float | string | bool | null | array | Check $check = null){
        
        $value = $this->posts[$name]??null;

        
        
        if (gettype($check)=='object'){
            
            if ($check->title == '' ) $check->title = $name;

            if ($check->check($value)){
                return $check->value;
            }else{
                
                throw new \Exception($check->message);
            }
        }else{
             
            if (is_null($value)){
                return $check;
            }else{
                return $value;
            }
        }
    }

    /**
     * 获取GET的值
     * 
     * 第二个参数为Check 类型时，验证参数，其他类型为默认值
     * 
     * @param string $name
     * @param mixed $default | Check $check
     * @return mixed
     */
    public function get($name,int | float | string | bool | null | Check $check = null){

        $value = $this->gets[$name]??null;
        
        if (gettype($check)=='object'){
            
            if ($check->title == '' ) $check->title = $name;


            if ($check->check($value)){
                
                return $check->value;
            }else{
                throw new \Exception($check->message);
            }
        }else{
            if (is_null($value)){
                return $check;
            }else{
                return $value;
            }
        }
    }
}